package day03_ThreadPool.demo_network_Socket.TCP_ChatView;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ChatView {
    public static void main(String[] args) throws Exception{
        JFrame frame= new JFrame("聊天窗口");

        JTextArea jTextArea= new JTextArea();
        JScrollPane scrollPane= new JScrollPane(jTextArea);
        frame.add(scrollPane, BorderLayout.CENTER); //边框布局

        JTextField jTextField= new JTextField();
        frame.add(jTextField, BorderLayout.SOUTH);
        frame.setLocation(300,300);
        frame.setVisible(true);
        frame.setResizable(true);
        frame.setSize(600,600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ServerSocket serverSocket=new ServerSocket(10002);

        jTextField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode()== KeyEvent.VK_ENTER){
                    Date date= new Date();
                    SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    jTextArea.append(simpleDateFormat.format(date)+"         "+jTextField.getText()+"\n");

                    try {
                        Socket socket= serverSocket.accept();
                        DataInputStream dataInputStream= new DataInputStream(socket.getInputStream());
                        InetAddress ip= socket.getInetAddress();
                        jTextArea.append(ip+"ip:    "+simpleDateFormat.format(date)+":    "+dataInputStream.readUTF()+"\n");
                        jTextField.setText("");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });
    }
}
